﻿using CommandLine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;

namespace win_service_cmd
{
    class Program
    {
        public class Options
        {

            [Option('s', "search", Required = false, HelpText = "搜索关键字（显示名、服务名、描述）")]
            public string Search { get; set; }


            [Option('p', "processId", Required = false, HelpText = "搜索进程ID，可模糊搜索")]
            public string ProcessId { get; set; }


            [Option('e', "executePath", Required = false, HelpText = "搜索可执行文件路径，可模糊搜索")]
            public string ExecutePath { get; set; }
        }
        static void Main(string[] args)
        {
            Parser.Default.ParseArguments<Options>(args)
                   .WithParsed<Options>(o =>
                   {
                       if (!string.IsNullOrEmpty(o.Search))
                       {
                           SearchAllService(o.Search);
                       }
                       else if (!string.IsNullOrEmpty(o.ProcessId))
                       {
                           SearchProcessIdService(o.ProcessId);
                       }
                       else if (!string.IsNullOrEmpty(o.ExecutePath))
                       {
                           SearchPathNameService(o.ExecutePath);
                       }
                       else
                       {
                           PrintAllService();
                       }
                   });
            
        }

        static string DefaultStr(string val,string defval)
        {
            if (string.IsNullOrEmpty(val))
            {
                return defval;
            }
            return val;
        }

        static void SearchAllService(string keyword)
        {
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Service");
                foreach (ManagementObject queryObj in searcher.Get())
                {
                    string displayName = queryObj["DisplayName"]!=null?queryObj["DisplayName"].ToString():"";
                    string Name = queryObj["Name"] != null ? queryObj["Name"].ToString():"";
                    string Description = queryObj["Description"] != null ? queryObj["Description"].ToString():"";
                    if (displayName.IndexOf(keyword)>=0 
                        || Name.IndexOf(keyword) >= 0
                        || Description.IndexOf(keyword) >= 0)
                    {
                        Console.WriteLine("显示名称: {0}", queryObj["DisplayName"]);
                        Console.WriteLine("服务名: {0}", queryObj["Name"]);
                        Console.WriteLine("描述: {0}", queryObj["Description"]);
                        Console.WriteLine("可执行文件路径: {0}", queryObj["PathName"]);
                        Console.WriteLine("状态: {0}", queryObj["State"]);
                        Console.WriteLine("进程ID: {0}", queryObj["ProcessId"]);
                        Console.WriteLine("-----------------------------------");
                    }
                }
            }
            catch (ManagementException me)
            {

            }
        }

        static void SearchProcessIdService(string keyword)
        {
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Service");
                foreach (ManagementObject queryObj in searcher.Get())
                {
                    if (queryObj["ProcessId"].ToString().IndexOf(keyword)>=0)
                    {
                        Console.WriteLine("显示名称: {0}", queryObj["DisplayName"]);
                        Console.WriteLine("服务名: {0}", queryObj["Name"]);
                        Console.WriteLine("描述: {0}", queryObj["Description"]);
                        Console.WriteLine("可执行文件路径: {0}", queryObj["PathName"]);
                        Console.WriteLine("状态: {0}", queryObj["State"]);
                        Console.WriteLine("进程ID: {0}", queryObj["ProcessId"]);
                        Console.WriteLine("-----------------------------------");
                    }
                }
            }
            catch (ManagementException me)
            {

            }
        }

        static void SearchPathNameService(string keyword)
        {
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Service");
                foreach (ManagementObject queryObj in searcher.Get())
                {
                    if (queryObj["PathName"].ToString().IndexOf(keyword) >= 0)
                    {
                        Console.WriteLine("显示名称: {0}", queryObj["DisplayName"]);
                        Console.WriteLine("服务名: {0}", queryObj["Name"]);
                        Console.WriteLine("描述: {0}", queryObj["Description"]);
                        Console.WriteLine("可执行文件路径: {0}", queryObj["PathName"]);
                        Console.WriteLine("状态: {0}", queryObj["State"]);
                        Console.WriteLine("进程ID: {0}", queryObj["ProcessId"]);
                        Console.WriteLine("-----------------------------------");
                    }
                }
            }
            catch (ManagementException me)
            {

            }
        }
        static void PrintAllService()
        {
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Service");
                foreach (ManagementObject queryObj in searcher.Get())
                {
                    Console.WriteLine("显示名称: {0}", queryObj["DisplayName"]);
                    Console.WriteLine("服务名: {0}", queryObj["Name"]);
                    Console.WriteLine("描述: {0}", queryObj["Description"]);
                    Console.WriteLine("可执行文件路径: {0}", queryObj["PathName"]);
                    Console.WriteLine("状态: {0}", queryObj["State"]);
                    Console.WriteLine("进程ID: {0}", queryObj["ProcessId"]);
                    Console.WriteLine("-----------------------------------");
                }
            }
            catch (ManagementException me)
            {

            }
        }
    }
}
